﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Kgb.Model.Models;
using Kgb.Service.Repository;
using Kgb.Service.Repository.Interface;
using System.Net;

namespace Kgb.Service.Controllers
{
    public class LobbiesController : ApiController
    {
        //static readonly
        private ILobbyRepository _repository;

        public LobbiesController()
        { 
            _repository = new LobbyRepository();
        }

        public IQueryable<Lobby> GetAllLobbies()
        {
            return _repository.GetAll();
        }

        [HttpGet]
        public IQueryable<Room> Rooms(int id, int page, int take)
        {
            Lobby lobby = _repository.Get(id);
            if (lobby == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            
            RoomRepository roomRepository = new RoomRepository();

            var result = roomRepository.GetAllByLobby(lobby.Id);

            return result.Skip((page - 1) * take).Take(take);
        }

        public Lobby GetLobby(int id)
        {
            Lobby lobby = _repository.Get(id);
            if (lobby == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return lobby;
        }

        public HttpResponseMessage<Lobby> PostLobby(Lobby lobby)
        {
            lobby = _repository.Add(lobby);
            var response = new HttpResponseMessage<Lobby>(lobby, HttpStatusCode.Created);

            string uri = Url.Route(null, new { id = lobby.Id });
            response.Headers.Location = new Uri(Request.RequestUri, uri);
            return response;
        }

        public void PutLobby(int id, Lobby lobby)
        {
            lobby.Id = id;
            if (!_repository.Update(lobby))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public HttpResponseMessage DeleteLobby(int id)
        {
            _repository.Remove(id);
            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
}
